package com.example.springbootmodel.Utils;


import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * 文件上传工具类
 *
 * @author Conkis-tp
 */
public class FileUpload {

    private static SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");

    /***
     * @description: 上传文件(多文件)保存
     * @param: request
    		   elementName
    		   targetFilePath
     * @return: java.lang.String
     * @author: ym
     * @date: 21/12/27 10:20
     */
    public static String upload(HttpServletRequest request, String elementName, String targetFilePath) throws Exception {
        return upload(request, elementName, targetFilePath, true,false,null,null);
    }

    /***
     * @description: 添加时间前缀
     * @param: request
    		   elementName
    		   targetFilePath
     * @return: java.lang.String
     * @author: ym
     * @date: 21/12/27 10:28
     */
    public static String uploadByDate(HttpServletRequest request, String elementName, String targetFilePath) throws Exception {
        return upload(request, elementName, targetFilePath, true,true,null,null);
    }

    /***
     * @description: 上传文件(多文件)保存
     * @param: request
    		   elementName 元素名称
    		   targetFilePath 文件保存路径
    		   isAbsolute 是否返回绝对路径
    		   datePrefix 是否添加时间前缀
    		   prefixName 文件前缀
               regex 匹配符（截取文件名参数当目录）
     * @return: java.lang.String
     * @author: ym
     * @date: 21/12/27 10:20
     */
    public static String upload(HttpServletRequest request, String elementName, String targetFilePath
            , boolean isAbsolute, boolean datePrefix,String prefixName,String regex) throws Exception {
        // 转型为MultipartHttpRequest(重点的所在)
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件（根据前台的name名称得到上传的文件）
        List<MultipartFile> files = multipartRequest.getFiles(elementName);

        if (files == null || files.size() == 0) {
            // uploadify文件上传控件兼容
            files = multipartRequest.getFiles("Filedata");
            if (files == null || files.size() == 0) {
                return null;
            }
        }
        StringBuffer fileNames = new StringBuffer();
        for (int i = 0; i < files.size(); i++) {
            MultipartFile myfile = files.get(i);
            // 获取原始文件名
            String originalFilename = myfile.getOriginalFilename();
            if (!StringUtils.isEmpty(originalFilename)) {
                //生成文件名称
                String filename = null;
                if(datePrefix){
                    filename = format.format(Calendar.getInstance().getTime()) + "_" + originalFilename;
                }else if(prefixName != null && !"".equals(prefixName) ) {
                    filename = prefixName + originalFilename;
                }else{
                    filename = originalFilename;
                }
                // 输出目录
                String targetFilePathNew = targetFilePath;
                if(regex != null && regex != ""){
                    targetFilePathNew += RegexUtils.intercept(regex,originalFilename);
                }
                // 保存文件
                FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(targetFilePathNew, filename));
                // 路径
                if(isAbsolute){
                    fileNames.append(targetFilePathNew + "/" + filename).append(";");
                }else{
                    fileNames.append(filename).append(";");
                }
            }
        }
        return fileNames.toString();
    }
	
}
